from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

from utils.config.ModelConst import *

bs = BUSINESS_TYPE


# Create your models here.

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    """
    创建token
    :param sender:
    :param instance:
    :param created:
    :param kwargs:
    :return:
    """
    if created:
        Token.objects.create(user=instance)


class BaseModel(models.Model):
    """
    抽象类,继承对象可获得以下4个属性
    """
    is_active = models.BooleanField(verbose_name="是否有效",
                                    default=True)

    datetime_created = models.DateTimeField(verbose_name="创建时间",
                                            auto_now_add=True)
    modifier = models.ForeignKey(User,
                                 verbose_name="修改人",
                                 on_delete=models.PROTECT,
                                 # limit_choices_to=~Q(manger_profile=None),
                                 null=True,
                                 blank=True)

    datetime_modifier = models.DateTimeField(verbose_name="修改时间",
                                             auto_now=True)

    class Meta:
        abstract = True


# class BaseShowModel(models.Model):
#     """
#     抽象类,是否显示
#     """
#     is_show = models.BooleanField(verbose_name="是否显示",
#                                   default=True)
#
#     class Meta:
#         abstract = True
#
#
class BaseUUIDModel(models.Model):
    """
    抽象类,uuid
    """
    uuid = models.UUIDField(verbose_name="uuid", )

    class Meta:
        abstract = True


class SystemRegion(BaseModel):
    """

    """
    code = models.CharField(verbose_name="编号",
                            primary_key=True,
                            max_length=20)

    name = models.CharField(verbose_name="地区",
                            max_length=100)

    class Meta:
        verbose_name = "地区信息表"
        verbose_name_plural = "地区信息表"
        db_table = "system_region"

    def __str__(self):
        return "%s" % self.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class SystemWrong(models.Model):
    path = models.CharField(verbose_name="访问路径",
                            max_length=1000,
                            null=True,
                            blank=True)
    method = models.CharField(verbose_name="方法",
                              max_length=10,
                              null=True,
                              blank=True)
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             on_delete=models.PROTECT,
                             related_name="system_wrong_user",
                             null=True,
                             blank=True)
    data = models.TextField(verbose_name="参数",
                            null=True,
                            blank=True
                            )
    ip_address = models.CharField(verbose_name="请求ip地址",
                                  max_length=20,
                                  null=True,
                                  blank=True)
    error = models.TextField(verbose_name="发生错误",
                             null=True,
                             blank=True)
    error_code = models.CharField(verbose_name="错误码",
                                  max_length=10,
                                  null=True,
                                  blank=True)
    datetime_created = models.DateTimeField(verbose_name="创建时间",
                                            auto_now_add=True)

    class Meta:
        verbose_name = "系统错误表"
        verbose_name_plural = "轮播图仓库表"
        db_table = "system_wrong"

    def __str__(self):
        return self.error_code

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class SystemUserRecord(models.Model):
    path = models.CharField(verbose_name="访问路径",
                            max_length=1000,
                            null=True,
                            blank=True)
    method = models.CharField(verbose_name="方法",
                              max_length=10,
                              null=True,
                              blank=True)
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             on_delete=models.PROTECT,
                             related_name="system_user_record_user",
                             null=True,
                             blank=True)
    data = models.TextField(verbose_name="参数",
                            null=True,
                            blank=True
                            )
    ip_address = models.CharField(verbose_name="请求ip地址",
                                  max_length=20,
                                  null=True,
                                  blank=True)
    datetime_created = models.DateTimeField(verbose_name="创建时间",
                                            auto_now_add=True)

    class Meta:
        verbose_name = "用户行为记录表"
        verbose_name_plural = "用户行为记录表"
        db_table = "system_user_record"

    def __str__(self):
        return str(self.datetime_created)

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class SystemImage(BaseModel):
    """
        图片信息表
    """
    TYPE_CHOICE = (
        (SYSTEM_IMAGE_SYSTEM, "系统图片"),
        (SYSTEM_IMAGE_GOODS, "商品图片"),
    )

    uuid = models.UUIDField(verbose_name="uuid", )
    type = models.IntegerField(verbose_name="类型",
                               choices=TYPE_CHOICE,
                               )
    url = models.CharField(verbose_name="地址",
                           max_length=500)

    class Meta:
        verbose_name = "图片信息表"
        verbose_name_plural = "图片信息表"
        db_table = "system_image"

    def __str__(self):
        return "%s" % self.url

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class Business(BaseModel):
    """
        商户信息配置
    """

    name = models.CharField(verbose_name="商户名称",
                            max_length=100)

    class Meta:
        verbose_name = "商户信息表"
        verbose_name_plural = "商户信息表"
        db_table = "business"

    def __str__(self):
        return "%s" % self.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class BusinessNotice(BaseModel):
    """
        商户通告
    """
    title = models.CharField(verbose_name="标题",
                             max_length=200)

    content = models.TextField(verbose_name="商品文章详情",
                               )

    class Meta:
        verbose_name = "商户信息表"
        verbose_name_plural = "商户信息表"
        db_table = "business_notice"

    def __str__(self):
        return "%s" % self.title

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class BusinessWish(BaseModel):
    """
       心愿单
    """
    user = models.ForeignKey(User,
                             on_delete=models.PROTECT,
                             verbose_name="用户",
                             related_name="business_wish_user")
    title = models.CharField(verbose_name="小标题",
                             max_length=100)
    content = models.TextField(verbose_name="内容", )

    class Meta:
        verbose_name = "心愿单表"
        verbose_name_plural = "心愿单表"
        db_table = "business_wish"

    def __str__(self):
        return "%s-%s" % (self.user.user_profile.nickname, self.title)

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class BusinessCoupon(BaseModel):
    """
       优惠卷
    """
    TYPE_CHOICE = (
        (COUPON_REDUCE_FULL, "满减"),
        (COUPON_REDUCE, "代金卷"),
        (COUPON_DISCOUNT_FULL, "满打折"),
        (COUPON_DISCOUNT, "打折"),
        (COUPON_GIVE, "满送"),
    )

    is_discount = models.BooleanField(verbose_name="是否在优惠期")

    is_single = models.BooleanField(verbose_name="是否单次卷",
                                    default=True)

    title = models.CharField(verbose_name="小标题",
                             max_length=100)

    type = models.IntegerField(verbose_name="类型",
                               choices=TYPE_CHOICE,
                               default=COUPON_REDUCE)
    amount = models.DecimalField(verbose_name="满额",
                                 decimal_places=2,
                                 max_digits=8,
                                 default=0)

    quota = models.DecimalField(verbose_name="活动额度",
                                decimal_places=2,
                                max_digits=8,
                                default=0)
    goods = models.ManyToManyField("Goods",
                                   verbose_name="相关优惠的商品",
                                   related_name="business_coupon_goods",
                                   blank=True)
    expiry_days = models.IntegerField(verbose_name="过期天数",
                                      default=1)

    class Meta:
        verbose_name = "优惠卷表"
        verbose_name_plural = "优惠卷表"
        db_table = "business_coupon"

    def __str__(self):
        return "%s-%s" % (self.title, self.get_type_display())

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class GoodsCategory(BaseModel):
    """
        商品分类
    """
    name = models.CharField(verbose_name="名称",
                            max_length=100)
    sort = models.IntegerField(verbose_name="排序",
                               help_text="越大越在前")

    class Meta:
        verbose_name = "商品分类表"
        verbose_name_plural = "商品分类表"
        db_table = "goods_category"

    def __str__(self):
        return "%s" % self.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class Goods(BaseModel):
    """
        商品
    """
    uuid = models.UUIDField(verbose_name="uuid",
                            primary_key=True)

    category = models.ForeignKey(GoodsCategory,
                                 verbose_name="类别",
                                 on_delete=models.PROTECT,
                                 related_name="goods_category",
                                 null=True)
    name = models.CharField(verbose_name="商品名称",
                            max_length=100)
    price = models.DecimalField(verbose_name="1份单价",
                                max_digits=15,
                                decimal_places=2,
                                default=0.01)
    unit = models.ForeignKey("GoodsUnit",
                             verbose_name="单位",
                             related_name="goods_unit",
                             on_delete=models.PROTECT,
                             null=True)
    unit_number = models.IntegerField(verbose_name="单位数量",
                                      default=1)
    is_top = models.BooleanField(verbose_name="是否置顶",
                                 default=False)
    sort = models.IntegerField(verbose_name="排序",
                               default=0)

    class Meta:
        verbose_name = "商户信息表"
        verbose_name_plural = "商户信息表"
        db_table = "goods"

    def __str__(self):
        return "%s" % self.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class GoodsUnit(BaseModel):
    """
        商品单位
    """
    TYPE_CHOICE = (
        (1, "克"),
        (2, "个"),
        (3, "盒"),
    )
    type = models.IntegerField(verbose_name="类型",
                               choices=TYPE_CHOICE,
                               default=1)

    class Meta:
        verbose_name = "商品单位表"
        verbose_name_plural = "商品单位表"
        db_table = "goods_unit"

    def __str__(self):
        return "%s" % str(self.type)

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class GoodsArticle(BaseModel):
    """
        商品详情
    """
    goods = models.OneToOneField(Goods,
                                 primary_key=True,
                                 verbose_name="商品",
                                 on_delete=models.CASCADE,
                                 related_name="goods_article")

    content = models.TextField(verbose_name="商品文章详情",
                               )

    class Meta:
        verbose_name = "商品详情表"
        verbose_name_plural = "商品详情表"
        db_table = "goods_article"

    def __str__(self):
        return "%s" % self.goods.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class GoodsAttr(BaseModel):
    """
       商品属性
    """
    goods = models.ForeignKey(Goods,
                              on_delete=models.PROTECT,
                              verbose_name="商品",
                              related_name="goods_attr")

    name = models.CharField(verbose_name="属性名称",
                            max_length=100)

    sort = models.IntegerField(verbose_name="排序",
                               default=0)

    price = models.DecimalField(verbose_name="单价",
                                max_digits=15,
                                decimal_places=2,
                                default=0.01)

    class Meta:
        verbose_name = "商品属性表"
        verbose_name_plural = "商品属性表"
        db_table = "goods_attr"

    def __str__(self):
        return "%s" % self.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class UserProfile(BaseModel):
    """
       用户扩展表
    """
    ROLE_CHOICE = (
        (1, "用户"),
    )
    is_test = models.BooleanField(verbose_name="是否测试账号",
                                  default=False)
    role = models.IntegerField(verbose_name="账号类型",
                               default=1)
    user = models.OneToOneField(User,
                                primary_key=True,
                                verbose_name="用户",
                                on_delete=models.CASCADE,
                                related_name="user_profile")

    # 基础信息
    nickname = models.CharField(verbose_name="昵称",
                                max_length=100)
    mobile = models.CharField(verbose_name="电话号码",
                              max_length=30,
                              blank=True,
                              null=True
                              )
    openid = models.CharField(verbose_name="微信号",
                              max_length=100,
                              blank=True,
                              null=True)
    avatar = models.CharField(verbose_name="头像",
                              max_length=1000,
                              null=True,
                              blank=True)

    serial_code = models.CharField(verbose_name="用户序列号",
                                   help_text="推荐码",
                                   max_length=10)

    referee_user = models.ForeignKey(User,
                                     on_delete=models.PROTECT,
                                     verbose_name="上级推荐人",
                                     related_name="user_referee_user",
                                     null=True,
                                     blank=True)

    class Meta:
        verbose_name = "客户信息表"
        verbose_name_plural = "客户信息表"
        db_table = "user_profile"

    def __str__(self):
        return "%s" % self.nickname

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class ManagerProfile(BaseModel):
    """
       管理员扩展表
    """
    is_active = models.BooleanField(verbose_name="是否激活",
                                    help_text="只有激活才能进行动作操作",
                                    default=True)
    user = models.OneToOneField(User,
                                primary_key=True,
                                verbose_name="用户",
                                on_delete=models.CASCADE,
                                related_name="manger_profile")
    # 基础信息
    nickname = models.CharField(verbose_name="昵称",
                                max_length=100)
    mobile = models.CharField(verbose_name="电话号码",
                              max_length=30,
                              blank=True,
                              null=True
                              )
    openid = models.CharField(verbose_name="微信号",
                              max_length=100,
                              blank=True)
    avatar = models.CharField(verbose_name="头像",
                              max_length=1000,
                              null=True,
                              blank=True)

    class Meta:
        verbose_name = "管理员信息表"
        verbose_name_plural = "管理员信息表"
        db_table = "manger_profile"

    def __str__(self):
        return "%s" % self.nickname

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class CouponRecord(BaseModel):
    """
    用户优惠卷
    """
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             on_delete=models.CASCADE,
                             related_name="coupon_record_user")
    coupon = models.ForeignKey(BusinessCoupon,
                               verbose_name="优惠卷",
                               on_delete=models.CASCADE,
                               related_name="coupon_record_coupon")
    datetime_created = models.DateTimeField(verbose_name="领取时间",
                                            auto_now_add=True)
    datetime_expiry = models.DateTimeField(verbose_name="过期时间",
                                           null=True,
                                           blank=True, )
    is_used = models.BooleanField(verbose_name="是否使用",
                                  default=False)

    class Meta:
        verbose_name = "用户优惠卷"
        verbose_name_plural = "用户优惠卷"
        db_table = "coupon_record"

    def __str__(self):
        return "%s-%s" % (self.user.user_profile.nickname, self.coupon.title)

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class UserPointRecord(BaseModel):
    """
    用户积分记录表
    """
    TYPE_CHOICE = (
        (POINT_ADD, "入账"),
        (POINT_REDUCE, "兑现"),
    )

    user = models.ForeignKey(User,
                             verbose_name="用户",
                             on_delete=models.CASCADE,
                             related_name="user_point_record")
    order = models.ForeignKey("OrderRecord",
                              verbose_name="订单",
                              on_delete=models.CASCADE,
                              related_name="user_coupon_record_coupon")
    type = models.IntegerField(verbose_name="类型",
                               choices=TYPE_CHOICE,
                               default=0)
    amount = models.IntegerField(verbose_name="变动积分",
                                 default=1)
    last_amount = models.IntegerField(verbose_name="当前积分",
                                      help_text="变动之前的积分",
                                      null=True,
                                      blank=True, )

    class Meta:
        verbose_name = "用户积分记录表"
        verbose_name_plural = "用户积分记录表"
        db_table = "user_point_record"

    def __str__(self):
        return self.user.user_profile.nickname

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class UserGoodsCollect(BaseModel):
    """
       用户收藏
    """
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             on_delete=models.PROTECT,
                             related_name="user_goods_collect_user")

    goods = models.ForeignKey("Goods",
                              verbose_name="商品",
                              on_delete=models.PROTECT,
                              related_name="user_goods_collect_goods")

    class Meta:
        verbose_name = "用户收藏表"
        verbose_name_plural = "用户收藏表"
        db_table = "user_goods_collect"

    def __str__(self):
        return "%s-%s" % (self.user.user_profile.nickname, self.goods.name)

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class UserCarRecord(BaseModel):
    """
        购物车
    """
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             related_name="user_car_record_user",
                             on_delete=models.PROTECT)
    goods = models.ForeignKey(Goods,
                              verbose_name="商品",
                              related_name="user_car_record_goods",
                              on_delete=models.PROTECT)
    unit = models.ForeignKey("GoodsUnit",
                             verbose_name="单位",
                             related_name="user_car_record_unit",
                             on_delete=models.PROTECT,
                             null=True)
    number = models.IntegerField(verbose_name="数量",
                                 default=1)

    class Meta:
        verbose_name = "购物车"
        verbose_name_plural = "购物车"
        db_table = "user_car_record"

    def __str__(self):
        return "%s" % self.user.user_profile.nickname

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class OrderRecord(BaseModel):
    """
        订单表
    status goods goods_name count price total
    """
    STATUS_CHOICE = (
        (ORDER_RECORD_STATUS_NO, '未支付'),
        (ORDER_RECORD_STATUS_PAY, '已支付'),
        (ORDER_RECORD_STATUS_FINISH, '已完成'),
        (ORDER_RECORD_STATUS_CLOSE, '已关闭')
    )
    user = models.ForeignKey(User,
                             verbose_name="用户",
                             related_name="order_record_user",
                             on_delete=models.PROTECT)
    amount = models.DecimalField(verbose_name="总额",
                                 max_digits=15,
                                 decimal_places=2,
                                 default=0.01)
    count = models.IntegerField(verbose_name="总件数",
                                default=1)
    goods_info = models.CharField(verbose_name="商品信息",
                                  max_length=2000)
    status = models.IntegerField(verbose_name="状态",
                                 choices=STATUS_CHOICE,
                                 default=ORDER_RECORD_STATUS_NO)

    class Meta:
        verbose_name = "订单表"
        verbose_name_plural = "订单表"
        db_table = "order_record"

    def __str__(self):
        return "%s" % self.user.user_profile.nickname

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class OrderConsumeRecord(BaseModel):
    """
        订单消费表
    """
    order = models.ForeignKey("OrderRecord",
                              verbose_name="订单",
                              related_name="order_consume_record_order",
                              on_delete=models.PROTECT)
    goods = models.ForeignKey("Goods",
                              verbose_name="商品",
                              related_name="order_consume_record_goods",
                              on_delete=models.PROTECT)
    count = models.IntegerField(verbose_name="件数",
                                default=1)
    price = models.DecimalField(verbose_name="单价",
                                max_digits=15,
                                decimal_places=2,
                                default=0.01)
    amount = models.DecimalField(verbose_name="总价",
                                 max_digits=15,
                                 decimal_places=2,
                                 default=0.01)

    class Meta:
        verbose_name = "订单消费表"
        verbose_name_plural = "订单消费表"
        db_table = "order_consume_record"

    def __str__(self):
        return "%s" % self.order.goods_info

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class OrderComment(BaseModel):
    """
        订单评价表
    """

    order = models.ForeignKey("OrderRecord",
                              verbose_name="订单",
                              related_name="order_comment_order",
                              on_delete=models.PROTECT)
    content = models.TextField(verbose_name="评价")

    class Meta:
        verbose_name = "订单消费表"
        verbose_name_plural = "订单消费表"
        db_table = "order_comment"

    def __str__(self):
        return "%s" % self.order.goods_info

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class PurchaseRecord(BaseModel):
    """
    进货单
    """
    PURCHASE_CHOICE = (
        (0, "自运"),
        (1, "捎带")
    )

    uuid = models.UUIDField(verbose_name="uuid",
                            primary_key=True)
    type = models.IntegerField(verbose_name="进货方式",
                               choices=PURCHASE_CHOICE,
                               default=0)
    freight_cost = models.DecimalField(verbose_name="货运成本",
                                       max_digits=15,
                                       decimal_places=2,
                                       default=0
                                       )

    class Meta:
        verbose_name = "进货单表"
        verbose_name_plural = "进货单表"
        db_table = "purchase_record"

    def __str__(self):
        return "%s" % str(self.datetime_created)

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class PurchaseDetailRecord(BaseModel):
    """
    进货详情
    """
    purchase = models.ForeignKey(PurchaseRecord,
                                 verbose_name="进货单",
                                 related_name="purchase_detail_record",
                                 on_delete=models.PROTECT)
    goods = models.ForeignKey(Goods,
                              verbose_name="商品信息",
                              related_name="purchase_detail_record_goods",
                              on_delete=models.PROTECT)
    price = models.DecimalField(verbose_name="进货价",
                                max_digits=15,
                                decimal_places=2,
                                default=1)
    unit = models.ForeignKey("GoodsUnit",
                             verbose_name="进货单位",
                             related_name="purchase_detail_record_unit",
                             on_delete=models.PROTECT,
                             null=True,
                             blank=True)
    number = models.DecimalField(verbose_name="进货数量",
                                 max_digits=15,
                                 decimal_places=2,
                                 default=1)

    class Meta:
        verbose_name = "进货详情表"
        verbose_name_plural = "进货详情表"
        db_table = "purchase_detail_record"

    def __str__(self):
        return "%s" % self.goods.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class Feedback(BaseModel):
    """
       用户反馈
    """
    user = models.ForeignKey(User,
                             verbose_name="反馈用户",
                             related_name="feedback_user",
                             on_delete=models.PROTECT,
                             null=True,
                             blank=True
                             )

    content = models.TextField(verbose_name="反馈信息", )

    class Meta:
        verbose_name = "反馈表"
        verbose_name_plural = "反馈表"
        db_table = "feedback"

    def __str__(self):
        return "%s" % self.user.user_profile.nickname if self.user and self.user.user_profile else ""

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()


class BusinessActivity(BaseModel):
    """
       活动
    """
    TYPE_CHOICE = (
        (COUPON_REDUCE_FULL, "满减"),
        (COUPON_REDUCE, "代金卷"),
        (COUPON_DISCOUNT_FULL, "满打折"),
        (COUPON_DISCOUNT, "打折"),
        (COUPON_GIVE, "满送"),
    )

    name = models.CharField(verbose_name="活动名称",
                            max_length=100)

    type = models.IntegerField(verbose_name="类型",
                               choices=TYPE_CHOICE,
                               default=10)

    amount = models.DecimalField(verbose_name="满额",
                                 decimal_places=2,
                                 max_digits=8,
                                 default=0)

    quota = models.DecimalField(verbose_name="活动额度",
                                decimal_places=2,
                                max_digits=8,
                                default=0)

    goods = models.ManyToManyField("Goods",
                                   verbose_name="优惠之内的商品",
                                   related_name="business_activity_goods",
                                   blank=True
                                   )

    datetime_start = models.DateTimeField(verbose_name="开始时间",
                                          null=True,
                                          blank=True)

    datetime_end = models.DateTimeField(verbose_name="结束时间",
                                        null=True,
                                        blank=True)

    content = models.TextField(verbose_name="活动详情",
                               null=True,
                               blank=True)

    class Meta:
        verbose_name = "活动表"
        verbose_name_plural = "活动表"
        db_table = "business_activity"

    def __str__(self):
        return "%s" % self.name

    def delete(self, using=None, keep_parents=False):
        self.is_active = False
        return self.save()
